import pymysql
from backend.config.db_config import DB_CONFIG
import pymysql

class DatabaseConnection:
    _instance = None
    _connection = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(DatabaseConnection, cls).__new__(cls)
        return cls._instance
    
    def connect(self):
        if self._connection is None or self._connection.open is False:
            try:
                self._connection = pymysql.connect(
                    host=DB_CONFIG['host'],
                    user=DB_CONFIG['user'],
                    password=DB_CONFIG['password'],
                    database=DB_CONFIG['database'],
                    port=DB_CONFIG['port'],
                    cursorclass=pymysql.cursors.DictCursor
                )
                print("数据库连接成功")
            except pymysql.MySQLError as e:
                print(f"数据库连接失败: {e}")
                raise
        return self._connection
    
    def disconnect(self):
        if self._connection is not None and self._connection.open:
            self._connection.close()
            self._connection = None
            print("数据库连接已关闭")
    
    def get_cursor(self):
        connection = self.connect()
        return connection.cursor()
    
    def commit(self):
        if self._connection is not None and self._connection.open:
            self._connection.commit()
    
    def rollback(self):
        if self._connection is not None and self._connection.open:
            self._connection.rollback()